<?php
namespace app\web\service;

use think\Db;


/**
 * 中移互联
 */
class Cmicrwx extends BaseSever
{

    /**
     * 报文返回格式
     * */
    public function returnMsg($param,$body){

        $reqTime = $sign = $transactionId = '';
        if( isset($param['contractRoot']) ){
            $reqTime = $param['contractRoot']['head']['reqTime'];
            $sign = $param['contractRoot']['head']['sign'];
            $transactionId = $param['contractRoot']['head']['transactionId'];
        }
        $data = [
            'contractRoot'  =>  [
                'head'=>[
                    "reqTime" => $reqTime,
                    "sign" => $sign,
                    "transactionId" => $transactionId,
                ],
                'body' =>$body
            ]
        ];
        return $data;

    }

    /**
     * 异步回调接口
    */
    public function commonBusinessOpenCallback($param,$info){

        $channelCode = $param['contractRoot']['head']['channelCode'];
        $rightsId = $param['contractRoot']['body']['rightsId'];
        $orderItemId = $param['contractRoot']['body']['orderItemId'];
        $transactionId = $param['contractRoot']['head']['transactionId'];

        $callbackDomain = isset($param['contractRoot']['head']['callbackDomain']) ? $param['contractRoot']['head']['callbackDomain'] : '';

        if(empty($callbackDomain) ){
            $url = "http://rmt.cmicrwx.cn/cmpp-api/external/commonBusinessOpenCallback";
        }else{
            $key = "24318544E3614311";
            $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
            $url = openssl_decrypt($callbackDomain,"AES-128-ECB",$key);
        }

        $msg = $info['msg'];
        $recoId = $info['recoId'];
        $status = $info['status'];

        list($usec, $sec) = explode(" ", microtime());
        $msec=round($usec*1000);
        if( strlen($msec) < 3) $msec .= 0;

        $data = [
            "contractRoot" => [
                'head' => [
                    "channelCode" => $channelCode,
                    "reqTime" => date('YmdHis', time()).$msec,
                    "sign" => '',
                    "apiId" => '200044',//正式环境
                    // "apiId" => '200046',//测试环境
                    "transactionId" => $transactionId,
                    // "callbackDomain" => $callbackDomain,
                    "version" => '1.0',
                ],
                'body'=>[
                    'orderItemId' => $orderItemId,
                    'rightsId' => $rightsId,
                    'status' => $status,
                    'msg' =>$msg,
                    'recoId' =>$recoId,
                ],
            ]
        ];

        $privateKey = 'C35995B636771643';//正式环境
        // $privateKey = '8132621E4A431465';//测试环境
        $reqTime        = $data['contractRoot']['head']['reqTime'];
        $body           = json_encode($data['contractRoot']['body'],256);

        $req_sign = $transactionId . $reqTime . $privateKey . $body;
        $sign = md5($req_sign);
        $data['contractRoot']['head']['sign'] = $sign;
 
        $header = array('Content-Type:application/json;charset=UTF-8');
        $res = requestPostCurl($url,json_encode($data,256),$header);
        return $res;

        // return '{"contractRoot": {"head": {"reqTime": "string","sign": "string","transactionId": "string"},"body": {"resultCode":"0000","resultMsg":"成功"}}}';
    }

    /**
     * 获取券信息
     * */
    public function getCouponList($cmicrwx_info){
        $couponInfo = [];
        if(!empty($cmicrwx_info['act_id_list']) ){
            $act_ids = explode(',',$cmicrwx_info['act_id_list']);
            foreach( $act_ids as $k=>$v ){
                $couponInfo[] = [
                    'activity'      => $v, //活动ID
                    'channel'       => $this->skuinfo['skuname'], //渠道码（自定义）
                    'skuCodes'      => $this->skuinfo['skucode'], // skucode
                ];
            }
        }else{
            $this->setCouponInfo();
            $couponInfo = $this->getCouponInfo();
        }
        return $couponInfo;
    }

    /***
     * 集团运营中心子渠道列表
     * */
    public function cmicrwxChannel($channel_id,$skucode=''){
        $channel_id = $channel_id ? $channel_id : 0;
        $key = $channel_id . '_' .$skucode;
        $res1 = $this->redis->hExists("cmicrwx_list",$key);
        if($res1){
            $cmicrwx_list = $this->redis->hget("cmicrwx_list",$key);
            return json_decode($cmicrwx_list,256);
        }

        $skuinfo_channel = Db::name("act_cmicrwx_list")->where("channel_id",$channel_id)->where("skucode",$skucode)->find();
        if( !empty($skuinfo_channel) ){
            $this->redis->hset("cmicrwx_list",$key,json_encode($skuinfo_channel));
            return $skuinfo_channel;
        }
        $data = [
            "channel_id"=>"0",
            "channel_name"=>"",
            "act_id_list"=>"",
            "is_open"=>1,
            "is_sms_four"=>"",
            "sms_template_four"=>"",
            "is_sms_six"=>"",
            "sms_template_six"=>"",
            "is_sms"=>"",
            "sms_template"=>"",
            "act_id_list_err"=>"",
        ];

        $info = Db::name("act_cmicrwx_list")->where("channel_id",$channel_id)->where("skucode=''")->find();
        if( empty($info) ) return $data;

        $info['skucode'] = $skucode;
        unset($info['id']);

        Db::name("act_cmicrwx_list")->insert($info);

        $this->redis->hset("cmicrwx_list",$key,json_encode($info));

        return $info;
    }

    /**
     * 获取短信模板子渠道到账短信
     * */
    public function getSubSmsTemplate($info,$reserved2,$skucode){
        $sub_channel_info = $this->cmicrwxChannel($reserved2,$skucode);
        if( $info['status_code'] == 401  ){
            return $sub_channel_info['sms_template'];
        }else if( $info['status_code'] == 410 && $info['detailState'] == 5){
            return $sub_channel_info['sms_template_two'];
        }
        return '';
    }
}